
<template>
  <!-- 角色页 -->
  <div class='group'>
    <div class="table_add">
      <el-button type="primary" @click="add(false)">添加角色</el-button>
    </div>
    <div class="table-item">
      <el-table :data="state.roleList" border>
        <el-table-column prop="name" label="角色名称"></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="text" @click="onUpdateRolePermission(scope.row)">授权</el-button>
            <el-button type="text" @click="add(scope.row)">编辑</el-button>
            <el-button type="text" @click="onDelRole(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <!-- 添加弹窗 -->
  <el-dialog v-model="state.roleDialogVisible" :title="state.roleDialogVisibleTitle" width="30%" :before-close="() => {
    state.roleDialogVisible = false
  }">


    <div class="item">
      <el-form label-position="top" label-width="100px" :rules="state.rules" :model="state.FormData"
        style="max-width: 460px">
        <el-form-item label="角色名称：" prop="name">
          <el-input v-model="state.FormData.name" />
        </el-form-item>
        <el-form-item label="角色描述：" prop="description">
          <el-input type="textarea" v-model="state.FormData.description" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="onAddRole">
          添加
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 授权 弹窗 -->
  <el-dialog v-model="state.rolePermissionDialogVisible" title="角色授权" width="30%" :before-close="() => {
    state.rolePermissionDialogVisible = false
  }">
    <div class="item">
      <el-form>
        <el-form-item>
          <el-tree :data="state.permissionTree" :default-expanded-keys="state.roleAllPermissions"
            :default-checked-keys="state.roleAllPermissions" node-key="permission" :props="state.defaultProps"
            show-checkbox ref="permissionRef" />
        </el-form-item>
        <el-form-item>
          <el-button @click="resetChecked">清空</el-button>
          <el-button type="primary" @click="setPermission">确认</el-button>
        </el-form-item>
      </el-form>

    </div>
  </el-dialog>
  <!-- 树状结构 -->
</template>
<script setup lang='ts'>
import { ref, onMounted, reactive } from 'vue'
import { deleteRoles, getAllRoles, updateRole, updateRolePermission, addRole, getPermissionsOfRole } from '@/api/system/role'
import { ComponentInternalInstance, getCurrentInstance } from 'vue';
// 导入权限树
import permissionTree from '@/router/permissionTree'
import { ElTree } from 'element-plus'
const { proxy } = getCurrentInstance() as ComponentInternalInstance
// 属性
const state = reactive({
  // 列表数据
  roleList: [],
  // 控制显示 添加角色 弹窗
  roleDialogVisible: false,
  // 显示 添加角色//编辑角色 弹窗
  roleDialogVisibleTitle: '',
  // 控制显示 角色授权 弹窗
  rolePermissionDialogVisible: false,
  // 添加角色//编辑角色 输入框内容
  FormData: {
    id: 0,
    name: '',
    description: ''
  },
  // 效验规则
  rules: {
    name: [{
      required: true,
      message: '请输入角色名称',
      trigger: 'blur'
    }],
    description: [{
      required: true,
      message: '请输入描述名称',
      trigger: 'blur'
    }],
  },
  // 权限树 规则结构
  defaultProps: {
    id: 'title',
    children: 'children',
    label: 'title'
  },
  // 权限树 数据
  permissionTree: permissionTree,
  // 角色所有权限
  roleAllPermissions: []
})
// 获取角色列表
const onGetAllRoles = () => {
  getAllRoles().then(res => {
    state.roleList = res.data
  })
}
// 删除角色
const onDelRole = (val: any) => {
  proxy?.$confirm('重置该用户密码，请谨慎操作！').then(() => {
    deleteRoles([val.id]).then(res => {
      console.log(res);
      if (res.data == 1) {
        proxy.$Notify.success('删除角色成功！')
        onGetAllRoles()
      }
    })
  })
}


// 添加 角色'
const add = (val: any) => {
  state.roleDialogVisible = true
  if (val) {
    state.FormData.id = val.id
    state.FormData.name = val.name
    state.FormData.description = val.description
    state.roleDialogVisibleTitle = '编辑角色'
  } else {
    state.FormData.id = 0
    state.FormData.name = ''
    state.FormData.description = ''
    state.roleDialogVisibleTitle = '添加角色'
  }
}
// 添加按钮
const onAddRole = () => {
  // 添加
  if (state.roleDialogVisibleTitle == '添加角色') {
    addRole(state.FormData).then(res => {
      if (res.data == 1) {
        proxy?.$Notify.success('添加角色成功！')
        state.roleDialogVisible = false
        onGetAllRoles()
      }
    })
    // 编辑
  } else {
    updateRole(state.FormData).then(res => {
      if (res.data == 1) {
        proxy?.$Notify.success('编辑角色成功！')
        state.roleDialogVisible = false
        onGetAllRoles()
      }
    })
  }
}


// 角色授权
const onUpdateRolePermission = (selecteRole: any) => {
  console.log(state.formData);

  state.roleAllPermissions = []
  state.formData = JSON.parse(JSON.stringify(selecteRole))
  state.rolePermissionDialogVisible = true,
    // 获取角色所有权限
    getPermissionsOfRole(selecteRole.id).then(res => {
      state.roleAllPermissions = res.data
    })
}
const permissionRef = ref<InstanceType<typeof ElTree>>()
// 清空 权限树
const resetChecked = () => {
  // 通过调用自己带方法 设置所以选择框为fasle
  permissionRef.value!.setCheckedKeys([], false)
}
// 修改 权限树
const setPermission = () => {
  // 通过调用 自带的方法 拿到选中的内容
  let nodes = permissionRef.value!.getCheckedNodes(false, false)
  let halfNodes = permissionRef.value.getHalfCheckedNodes()
  nodes.unshift.apply(nodes, halfNodes)
  // 设置 新的 
  let permission: InstanceType<typeof ElTree>[] = []
  // 重构赋值
  // 循环把 nodes里面的permission给到permission
  nodes.forEach(node => {
    if (node.permission) {
      permission.push(node.permission)
    }
  })

  // 组合
  let vo = {
    roleId: state.formData.id,
    permissions: permission
  }
  // 修改 权限树 内容
  updateRolePermission(vo).then((res) => {
    proxy?.$Notify.success('修改成功!')
    state.rolePermissionDialogVisible = false
    onGetAllRoles()
  })
}
// 重置数据
const onReset = () => {
  state.FormData.name = ''
  state.FormData.description = ''
}
onMounted(() => {
  onGetAllRoles()
})
</script>
<style lang='less' scoped>
.table_add {
  margin-bottom: 20px;
}
</style>